<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">商品名称</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="商品名称"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">分类</label>
        <el-select
          clearable
          v-model="query.categoryId"
          placeholder="请选择分类"
          class="filter-item"
          style="width: 185px;"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <label class="el-form-item-label">上下架状态</label>
        <el-select
          clearable
          v-model="query.status"
          placeholder="请选择状态"
          class="filter-item"
          style="width: 160px;"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in goodsStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">特价商品</label>
        <el-select
          clearable
          v-model="query.specialOffer"
          placeholder="请选择状态"
          class="filter-item"
          style="width: 160px;"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in specialOfferStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label class="el-form-item-label">上新商品</label>
        <el-select
          clearable
          v-model="query.isNew"
          placeholder="请选择状态"
          class="filter-item"
          style="width: 160px;"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in specialOfferStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :crud="crud"/>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission"/>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="60%"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px" style="padding: 0 20px">
          <el-form-item label="商品分类" prop="categoryId">
            <el-select v-model="form.categoryId" placeholder="请选择">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="主图" prop="img">
                <el-upload
                  :on-preview="handlePictureCardPreview"
                  :before-remove="handleBeforeRemove"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :headers="headers"
                  :file-list="fileList"
                  :action="qiNiuUploadApi"
                  list-type="picture-card"
                >
                  <i class="el-icon-plus"/>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="商品详情图">
                <el-upload
                  :on-preview="imageshandlePictureCardPreview"
                  :before-remove="imageshandleBeforeRemove"
                  :on-success="imageshandleSuccess"
                  :on-error="imageshandleError"
                  :headers="headers"
                  :file-list="fileLists"
                  :action="qiNiuUploadApi"
                  list-type="picture-card"
                >
                  <i class="el-icon-plus"/>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <!--<el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="视频">
                <el-input v-model="form.video" style="" />
              </el-form-item>
            </el-col>
          </el-row>-->

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="form.name" style=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品简介">
                <el-input v-model="form.toreInfo" style=""/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="原价" prop="originalPrice">
                <el-input v-model="form.originalPrice" style=""/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="虚拟销量" prop="ficti">
                <el-input v-model="form.ficti" style=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-button style="margin: 0 0 15px 40px;" plain @click="addPriceRules">添加商品规格</el-button>
              <el-button style="margin: 0 0 15px 15px;" plain @click="createPriceRules">生成规格</el-button>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-table
                :data="skuRules"
                height="200"
                border
                style="width: auto;margin-left: 40px;min-height: 100px!important;margin-bottom: 20px;"
              >
                <el-table-column
                  prop="specValues"
                  label="规格名称"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.specValues" placeholder="规格名称"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sales"
                  label="虚拟销量"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.sales" placeholder="虚拟销量"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sellPrice"
                  label="销售价"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.sellPrice" placeholder="请输入销售价"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="originalPrice"
                  label="原价"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.originalPrice" placeholder="请输入原价"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="forPurchasing"
                  label="限购数量"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.forPurchasing" placeholder="限购数量"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="stock"
                  label="库存"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.stock" placeholder="库存"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="unit"
                  label="单位"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.unit" placeholder="单位"/>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="unitPrice"
                  label="单价"
                >
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.unitPrice" placeholder="单价"/>
                  </template>
                </el-table-column>
                <el-table-column
                  fixed="right"
                  label="操作"
                  width="80"
                >
                  <template slot-scope="scope">
                    <el-popconfirm
                      title="删除不可恢复，你确定要删除吗？"
                      @onConfirm="deleteRow(scope.$index, skuRules)"
                    >
                      <el-button
                        slot="reference"
                        type="text"
                        size="small"
                      >
                        移除
                      </el-button>
                    </el-popconfirm>
                    <!--<el-button
                      type="text"
                      size="small"
                      @click.native.prevent="deleteRow(scope.$index, skuRules)"
                    >
                      移除
                    </el-button>-->
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <!--<el-form-item label="活动ID">
            <el-input v-model="form.activityId" style=""/>
          </el-form-item>
          <el-form-item label="vip折扣">
            <el-input v-model="form.vipDiscount" style=""/>
          </el-form-item>
          -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="form.supplierId" placeholder="请选择">
                  <el-option
                    v-for="item in supplierList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="品牌" prop="brandId">
                <el-select v-model="form.brandId" placeholder="请选择">
                  <el-option
                    v-for="item in brandList"
                    :key="item.id"
                    :label="item.brandName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!--<el-form-item label="商品详情">
            <el-input v-model="form.introduction" style=""/>
          </el-form-item>-->

          <!--  <el-form-item label="邮费(暂时不用)">
              <el-input v-model="form.postage" style=""/>
            </el-form-item>-->
          <!-- <el-form-item label="运费模板ID（暂时不用）">
             <el-input v-model="form.tempId" style=""/>
           </el-form-item>-->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="状态">
                <el-radio v-model="form.status" :label="true">上架</el-radio>
                <el-radio v-model="form.status" :label="false">下架</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否特价">
                <el-radio v-model="form.specialOffer" :label="1">是</el-radio>
                <el-radio v-model="form.specialOffer" :label="0">否</el-radio>
                <!--<el-radio v-for="item in dict.status" :key="item.id" v-model="form.isHot" :label=item.label>{{item.label}}
                </el-radio>-->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否新品">
                <el-radio v-model="form.isNew" :label="true">是</el-radio>
                <el-radio v-model="form.isNew" :label="false">否</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="id" label="id"/>
        <el-table-column prop="img" label="主图">
          <template slot-scope="scope">
            <el-image
              style="width: 80px; height: 80px"
              :src="scope.row.img"
              fit="cover"
            />
          </template>

        </el-table-column>
        <el-table-column prop="name" label="商品名称"/>
        <!--<el-table-column prop="toreInfo" label="商品简介"/>-->
        <el-table-column prop="originalPrice" label="原价"/>
        <el-table-column prop="ficti" label="虚拟销量"/>
        <el-table-column prop="sort" label="排序(大到小)"/>
        <!--<el-table-column prop="supplierId" label="供应商ID" />-->
        <!-- <el-table-column prop="brandId" label="品牌ID" />-->
        <el-table-column prop="createTime" label="创建时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="specialOffer" label="是否特价商品">
          <template slot-scope="scope">
            {{ dict.label.status_v[scope.row.specialOffer] }}
          </template>
        </el-table-column>
        <el-table-column prop="isNew" label="是否新品">
          <template slot-scope="scope">
            {{ dict.label.status[scope.row.isNew] }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="上下架状态">
          <template slot-scope="scope">
            {{ dict.label.goods_status[scope.row.status] }}
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','ycGoods:edit','ycGoods:del']" fixed="right" label="操作" width="150px"
                         align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
  import crudYcGoods from '@/api/goods/goods'
  import CRUD, {presenter, header, form, crud} from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'
  import crudYcCategory from '@/api/goods/goodsCategory'
  import crudYcBrand from '@/api/goods/goodsBrand'
  import crudYcSupplier from '@/api/goods/supplier'
  import {mapGetters} from 'vuex'
  import {getToken} from '@/utils/auth'
  import crudQiNiu from '@/api/tools/qiniu'

  const defaultForm = {
    id: null,
    img: null,
    sliderImage: null,
    name: null,
    toreInfo: null,
    activityId: null,
    categoryId: null,
    originalPrice: null,
    vipDiscount: null,
    ficti: null,
    status: null,
    supplierId: null,
    brandId: null,
    introduction: null,
    postage: null,
    tempId: null,
    video: null,
    isHot: null,
    specialOffer: null,
    sort: null,
    isNew: null,
  }
  export default {
    name: 'YcGoods',
    components: {pagination, crudOperation, rrOperation, udOperation},
    mixins: [presenter(), header(), form(defaultForm), crud()],
    dicts: ['goods_status', 'status' ,'status_v'],
    cruds() {
      return CRUD({title: '商品', url: 'api/ycGoods', sort: 'id,desc', crudMethod: {...crudYcGoods}})
    },
    data() {
      return {
        headers: {
          'Authorization': getToken()
        },
        permission: {
          add: ['admin', 'ycGoods:add'],
          edit: ['admin', 'ycGoods:edit'],
          del: ['admin', 'ycGoods:del']
        },
        rules: {
          name: [
            {required: true, message: '商品名称不能为空', trigger: 'blur'}
          ],
          categoryId: [
            {required: true, message: '分类不能为空', trigger: 'blur'}
          ],
          originalPrice: [
            {required: true, message: '原价不能为空', trigger: 'blur'}
          ],
          ficti: [
            {required: true, message: '虚拟销量不能为空', trigger: 'blur'}
          ]
        },
        queryTypeOptions: [
          {key: 'id', display_name: 'id'},
          {key: 'name', display_name: '商品名称'},
          {key: 'activityId', display_name: '活动ID'},
          {key: 'categoryId', display_name: '分类id'},
          {key: 'status', display_name: '上下架状态1.上架 0.下架'},
          {key: 'supplierId', display_name: '供应商ID'},
          {key: 'brandId', display_name: '品牌ID'},
          {key: 'isHot', display_name: '是否热卖'},
          {key: 'isNew', display_name: '是否新品'}
        ],
        categoryList: [],
        brandList: [],
        supplierList: [],
        // img
        dialogImageUrl: '',
        dialogVisible: false,
        fileList: [],
        pictures: [],
        // images
        dialogImageUrls: '',
        dialogVisibles: false,
        fileLists: [],
        picturess: [],
        // sku
        skus: [],
        skuRules: [],
        //
        goodsStatus:[
          {value: true, label: '上架'},
          {value: false, label: '下架'}
        ],
        specialOfferStatus:[
          {value: 1, label: '是'},
          {value: 0, label: '否'}
        ],
        isNewStatus:[
          {value: true, label: '是'},
          {value: false, label: '否'}
        ],
      }
    },
    computed: {
      ...mapGetters([
        'qiNiuUploadApi'
      ])
    },
    methods: {
      // 钩子：在获取表格数据之前执行，false 则代表不获取数据
      [CRUD.HOOK.beforeRefresh]() {
        this.getTwoCate()
        this.getGoodsBrand()
        this.getGoodsSupplier()
        // this.getCategoryTree();
        return true
      },
      // 新建 - 之前
      [CRUD.HOOK.beforeToAdd]() {
        this.skus = []
        this.skuRules = []
        //
        this.dialogImageUrl = ''
        this.dialogVisible = false
        this.fileList = []
        this.pictures = []
        //
        this.dialogImageUrls = ''
        this.dialogVisibles = false
        this.fileLists = []
        this.picturess = []
        return true
      },
      // 编辑 - 之前
      [CRUD.HOOK.beforeToEdit]() {
        //
        this.fileList = []
        this.pictures = []
        if (this.form.img) {
          const url = this.form.img
          this.fileList.push({url})
        }
        //
        this.fileLists = []
        this.picturess = []
        this.fileLists = JSON.parse(this.form.sliderImage)
        console.log('this.fileLists')
        console.log(this.fileLists)
        return true
      },
      // 开始 "新建/编辑" - 之后
      [CRUD.HOOK.afterToCU]() {
        // this.fileList = this.form.img;
        //

        //
        /* this.fileLists =[];
              var imgss = JSON.parse( this.form.sliderImage );
              console.log(imgss);
              for (let i =1;i<imgss.length;i++){
                const urls = imgss[i];
                console.log("urls");
                console.log(urls);
                this.fileLists.push({ url });
              }
              console.log(this.fileLists);*/
        //
        if (this.form.id) {
          this.getSku(this.form.id)
        }
        console.log(this.form)
        return true
      },
      // 提交前
      [CRUD.HOOK.beforeSubmit]() {
        const _t = this
        // 头图
        console.log('_t.pictures=======')
        console.log(_t.pictures)
        if (_t.pictures.length > 0) {
          _t.form.img = _t.pictures[0].url
        }
        // 轮播图
        var imgs = new Array()
        _t.picturess.forEach(function (item, index, array) {
          var img = new Object()
          img.url = array[index].url
          imgs[index] = img
        })
        console.log(imgs)
        _t.form.sliderImage = JSON.stringify(imgs)
        // sku
        console.log('/////////////////')
        console.log(_t.skus)
        if (_t.skus != null) {
          _t.form['skus'] = _t.skus
        } else {
          this.$message.error('错误提示：优惠规则未生成，请点击生成规则！')
          return
        }
        console.log('_t.form')
        console.log(_t.form)
        return true
      },
      // 头图
      handleSuccess(response, file, fileList) {
        const uid = file.uid
        const id = response.id
        const url = response.data[0]
        this.pictures.push({uid, id, url})
      },
      handleBeforeRemove(file, fileList) {
        for (let i = 0; i < this.pictures.length; i++) {
          if (this.pictures[i].uid === file.uid) {
            crudQiNiu.del(Array.of(this.pictures[i].id)).then(res => {
            })
            return true
          }
        }
      },
      handlePictureCardPreview(file) {
        console.log('handlePictureCardPreview')
        console.log(file)
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 监听上传失败
      handleError(e, file, fileList) {
        const msg = JSON.parse(e.message)
        this.$notify({
          title: msg.message,
          type: 'error',
          duration: 2500
        })
      },
      // 轮播图
      imageshandleSuccess(response, file, fileList) {
        const uid = file.uid
        const id = response.id
        const url = response.data[0]
        this.picturess.push({uid, id, url})
        console.log(this.picturess)
        console.log(file)
      },
      imageshandleBeforeRemove(file, fileList) {
        for (let i = 0; i < this.picturess.length; i++) {
          if (this.picturess[i].uid === file.uid) {
            crudQiNiu.del(Array.of(this.picturess[i].id)).then(res => {
            })
            return true
          }
        }
      },
      imageshandlePictureCardPreview(file) {
        this.dialogImageUrls = file.url
        this.dialogVisibles = true
      },
      // 监听上传失败
      imageshandleError(e, file, fileList) {
        const msg = JSON.parse(e.message)
        this.$notify({
          title: msg.message,
          type: 'error',
          duration: 2500
        })
      },
      //
      getTwoCate() {
        crudYcCategory.getUpIdIsNotNullList().then(res => {
          this.categoryList = res
          console.log('getUpIdIsNull')
          console.log(res)
        })
      },
      getCategoryTree() {
        crudYcCategory.getTree().then(res => {
          console.log('getTree')
          console.log(res)
        })
      },
      getGoodsBrand() {
        crudYcBrand.getBrandList().then(res => {
          this.brandList = res.content
          console.log('getGoodsBrand')
          console.log(res)
        })
      },
      getGoodsSupplier() {
        crudYcSupplier.getSupplierList().then(res => {
          this.supplierList = res.content
          console.log('getSupplierList')
          console.log(res)
        })
      },
      getSku(goodsId) {
        crudYcGoods.getGoodsSku(goodsId).then(res => {
          console.log('getGoodsSku')
          console.log(res)
          this.skus = res
          this.skuRules = res
        })
      },
      // 添加规则
      addPriceRules() {
        const _t = this
        var tem = {
          specValues: '',
          sales: '',
          sellPrice: '',
          originalPrice: '',
          forPurchasing: '',
          stock: '',
          unit: '',
          unitPrice: '',
          isForPurchasin: 'true'
        }
        _t.skuRules = _t.skuRules.concat(tem)
        console.log('_t.skuRules')
        console.log(_t.skuRules)
      },
      createPriceRules() {
        const _t = this
        if (_t.skuRules != '') {
          let st = false
          for (let i = 0; i < _t.skuRules.length; i++) {
            if (_t.skuRules[i].specValues == '') {
              st = false
              break
            } else if (_t.skuRules[i].sellPrice == '') {
              st = false
              break
            } else {
              st = true
              continue
            }
          }

          if (st) {
            _t.skus = _t.skuRules
            console.log('_t.skus')
            console.log(_t.skus)
            // _t.formData.priceValue = JSON.stringify(_t.skuRules);
            this.$message({
              message: '成功提示：优惠规则生成成功！',
              type: 'success'
            })
          } else {
            this.$message.error('错误提示：您有一条优惠规则未填写！')
          }
        } else {
          this.$message.error('错误提示：您有一条优惠规则未填写！')
        }
      },

      deleteRow(index, rows) {
        var ids = new Array()
        ids[0] = rows[0].id
        console.log(ids)
        crudYcGoods.deleteGoodsSku(ids).then(res => {
          console.log(res)
          this.$message({
            message: '操作提示：删除成功！',
            type: 'success'
          })
          rows.splice(index, 1)
        })
      }
    }
  }
</script>

<style scoped>

</style>
